const fs = require('fs')
const jwt = require('jsonwebtoken')
const userService = require('../service/userService')
const { secretPassword } = require('../utils/handle-password')
const errorTypes = require('../constants/error-type')
class AuthController {
  async verifyLogin(ctx, next) {
    const { username, password } = ctx.request.body
    //检验用户名或密码是否为空
    if (!username || !password) {
      const error = new Error(errorTypes.USERNAME_OR_PASSWORD_IS_EMPITY)
      return ctx.app.emit('error',error,ctx)
    }
    const result = await userService.getUserByUsername(username)
     //检验用户名是否存在
    if (result.length === 0) {
      const error = new Error(errorTypes.USERNAME_IS_NOT_EXIST)
      return ctx.app.emit('error',error,ctx)
    }
    const user = result[0]
    ctx.user = user
    //检验密码是否正确
    if (secretPassword(password) !== user.password) {
      const error = new Error(errorTypes.PASSWORD_IS_WRONG)
      return ctx.app.emit('error',error,ctx)
    }
    await next()
  }
  async verifyAuth(ctx, next) {
    const authorization = ctx.headers.authorization;
    if (!authorization) {
      const error = new Error(errorTypes.IS_NOT_AUTH)
      return ctx.app.emit('error',error,ctx)
    }
    try {
      const token = authorization.replace('Bearer ', '')
      const publicKey = fs.readFileSync('src/app/keys/public.key')
      const result = jwt.verify(token, publicKey, {
        alogirthms: ['RS256'],
        expiresIn: 60 * 60 * 24
      })
      ctx.user = result
      await next()
    } catch (err) {
      const error = new Error(errorTypes.TOKEN_IS_USELESS)
      return ctx.app.emit('error',error,ctx)
    }
  }

}
module.exports = new AuthController()